import json

import requests

BATCH_SIZE = 20

"""
此处是对代码分析模块的调用
请求格式为:
[
    {
        "repo_id": ...,
        "hash": ...
    },
    {
        "repo_id": ...,
        "hash": ...
    },
    ...
]
需要返回一个数组，格式为：
[
    {
        "result": "arm",
        "detail": {
            "file_path_new_1": {
                "arch_line": [
                    "行号", "行号1-行号2", ...
                ],
                "comments": {
                    "行号（变更后）": "单行注释内容",
                    "起始行号-结束行号": "多行注释内容"
                },
            },
            "file_path_new_2": {
                "arch_line": [
                    "行号", "行号1-行号2", ...
                ],
                "comments": {
                    "行号（变更后）": "单行注释内容",
                    "起始行号-结束行号": "多行注释内容"
                },
            },
        }
        ...
    },
    {
        "result": "",
        "detail": {}
    },
    ...

]
"""
def sa(request):
    print(request)
    if len(request) == 0:
        return []
    return [{
        "result": "",
        "detail": {}
    }] * (len(request))
    # return [{
    #     "result": "arm",
    #     "detail": {
    #         "protocol.h": {
    #             "arch_line": [
    #                 "行号", "行号1-行号2",
    #             ],
    #             "comments": {
    #                 "行号（变更后）": "单行注释内容",
    #                 "起始行号-结束行号": "多行注释内容"
    #             },
    #         }
    #     }
    # }] * (len(request) - 1) + [{
    #     "result": "",
    #     "detail": {}
    # }]


"""
此处是对自然语言处理模块的调用
请求相同,但仅返回result
"""
def nlp(request):
    from manage import get_service
    service_ip, service_port = get_service("nlp")
    results = []
    for arr in split_array(request):
        result = requests.post(f"http://{service_ip}:{service_port}/inference", json=arr)
        if result.status_code != 200:
            raise Exception(f"服务调用异常:调用失败-{result.status_code}")
        results.extend(json.loads(result.text))
    return results

def split_array(input_array):
    return [input_array[i:i+BATCH_SIZE] for i in range(0, len(input_array), BATCH_SIZE)]
